package com.spm.librarianmanagersystem.service.impl;

import com.spm.librarianmanagersystem.mapper.RenewMapper;
import com.spm.librarianmanagersystem.mapper.ReturnMapper;
import com.spm.librarianmanagersystem.pojo.Borrow;
import com.spm.librarianmanagersystem.service.RenewService;
import org.apache.ibatis.transaction.TransactionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.InvalidParameterException;
import java.util.Date;

@Service("RenewService")
public class RenewServiceImpl implements RenewService {
    @Autowired
    ReturnMapper returnMapper;

    @Autowired
    RenewMapper renewMapper;

    @Override
    @Transactional
    public String renew(String currentUserId, Integer borrowNum)
            throws InvalidParameterException, TransactionException {
        System.out.println(currentUserId);
        Borrow borrow = returnMapper.getBorrowRecord(borrowNum, currentUserId);

        // 验证是否有对应的借书记录
        if (borrow == null) {
            throw new InvalidParameterException("未找到借阅记录");
        }

        // 验证是否逾期
        Date now = new Date(System.currentTimeMillis());
        if (borrow.getDueTime().before(now)) {
            throw new TransactionException("已超过归还日期");
        }

        // 验证是否已经续借过
        if (borrow.getRenewed() == 1) {
            throw new TransactionException("已续借，不可再次续借");
        }

        // 续借图书, 增加借书一个周期
        long dueTimeStamp = 2 * borrow.getDueTime().getTime() - borrow.getBorrowStartTime().getTime();
        Boolean ok = renewMapper.updateBorrowForRenew(borrowNum, new Date(dueTimeStamp));
        if (ok == null || !ok) {
            throw new TransactionException("续借图书记录失败");
        }

        return "操作成功!";
    }
}
